package advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * @author 石小俊
 */
@Component
@Aspect
public class LoggerAdvice {

    @Pointcut(value = "execution(* service.*Impl.*(..))")
    public void pointcutName(){}

    @Before("pointcutName()")
    public void before(JoinPoint jp) {
        // 获取目标类
        Object target = jp.getTarget();
//        Object target = jp.getThis();
        // 获取目标方法
        Signature signature = jp.getSignature();
        // 获取参数列表
        Object[] args = jp.getArgs();
        System.out.println("前置通知:在" + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()) + "访问了" + signature.getName() + "方法,方法的参数列表为:" + Arrays.toString(args));
    }

    @AfterReturning(value = "pointcutName()",returning = "returnValue")
    public void afterReturning(JoinPoint jp, Object returnValue) {
        System.out.println("正常返回通知:" + jp.getSignature().getName() + "方法执行成功,方法的返回值为:" + returnValue);
    }

    @AfterThrowing(value = "pointcutName()",throwing = "e")
    public void afterThrowing(JoinPoint jp, Exception e) {
        System.out.println("异常通知:" + jp.getSignature().getName() + "方法执行遇到了异常,异常为:" + e);
    }

    @After("pointcutName()")
    public void after(JoinPoint jp) {
        System.out.println("后置通知:" + jp.getSignature().getName() + "方法执行结束");
    }

    @Around("pointcutName()")
    public Object around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕通知之前置通知");
        Object result = null;
        try {
            result = jp.proceed();
            System.out.println("环绕通知之正常返回通知");
        } catch (Throwable throwable) {
            System.out.println("环绕通知之异常通知");
        } finally {
            System.out.println("环绕通知之后置通知");
        }
        return result;
    }
}
